package com.comtop.topcloud.device.service.impl;

import com.alibaba.fastjson.JSON;
import com.comtop.topcloud.device.model.Command;
import com.comtop.topcloud.device.model.CommandRequest;
import com.comtop.topcloud.device.model.mysql.EventTable;
import com.comtop.topcloud.device.mapper.EventTableMapper;
import com.comtop.topcloud.device.service.EventTableService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 召读事件表 服务实现类
 * </p>
 *
 * @author 张俊彬
 * @since 2025-01-04
 */
@Slf4j
@Service
@AllArgsConstructor
public class EventTableServiceImpl extends ServiceImpl<EventTableMapper, EventTable> implements EventTableService {

    private final MqttClient mqttClient;

    @Override
    public Long sendCommand(CommandRequest params) {
        Long eventId = null;
        try {
            String deviceName = params.getDeviceName();
            String sn = params.getSn();
            String pKey = params.getProductKey();

            // 记录事件
            EventTable eventTable = createEventTable(deviceName, sn, "write");
            save(eventTable);

            // 创建命令
            Command command = createCommand(params, pKey, sn, eventTable);

            // 发布命令
            String jsonString = JSON.toJSONString(command);
            mqttClient.publish("/cloud/" + pKey + "/" + sn + "/cmd/set", jsonString.getBytes(StandardCharsets.UTF_8), 1, false);
            log.info("发送命令: {}", jsonString);
            log.info("主题: {}", "/cloud/" + pKey + "/" + sn + "/cmd/set");

            // 更新事件数据
            eventTable.setRequestData(jsonString);
            eventTable.setRequestTimestamp(System.currentTimeMillis() / 1000);
            updateById(eventTable);

            eventId = eventTable.getEventId(); // 返回EventId

        } catch (Exception e) {
            log.error("发送命令失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送命令失败", e); // 提供更多错误信息
        }
        return eventId;
    }

    private EventTable createEventTable(String deviceName, String sn, String eventType) {
        EventTable eventTable = new EventTable();
        eventTable.setTerminalName(deviceName);
        eventTable.setSerialNumber(sn);
        eventTable.setEventType(eventType);
        return eventTable;
    }

    private Command createCommand(CommandRequest params, String pKey, String sn, EventTable eventTable) {
        Command command = new Command();
        command.setPKey(pKey);
        command.setSn(sn);
        command.setType("cmd/set");
        long requestTimestamp = System.currentTimeMillis() / 1000;
        command.setTs(requestTimestamp);

        // 设置Data字段
        Command.Data data = new Command.Data();
        data.setSysid(String.valueOf(eventTable.getEventId()));  // 系统ID
        data.setMonitorName(params.getDeviceName());
        data.setM(params.getTagName());
        data.setV(params.getValue());

        command.setData(data);
        return command;
    }

}
